package com.qf.smsplatform.gateway.mq;

import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.gateway.netty4.NettyClient;
import com.qf.smsplatform.gateway.netty4.Utils.Command;
import com.qf.smsplatform.gateway.netty4.Utils.MsgUtils;
import com.qf.smsplatform.gateway.netty4.entity.CmppMessageHeader;
import com.qf.smsplatform.gateway.netty4.entity.CmppSubmit;
import com.qf.smsplatform.gateway.netty4.entity.ControlWindow;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ReceiveSmsFromMq {

    @Autowired
    private NettyClient nettyClient;

    /**
     * 消息接受  并发消费
     */
    @RabbitListener(queues = "${gateway.sendtopic}", containerFactory = "pointTaskContainerFactory")
    public void receive(StandardSubmit submit) throws IOException, InterruptedException {
        log.info("接收消息: submit = {}",submit);
        String mobile=submit.getDestMobile();     // 手机号
        String content=submit.getMessageContent();   // 短信内容
        String srcNumber = submit.getSrcNumber();   // 下发的源号码
        int sequenceId = MsgUtils.getSequence();   // 生成了一个唯一序列,sequenceId, 基于JVM内存实现的.   Redis,雪花算法
        submit.setSequenceId(sequenceId + "");  // 封装到submit对象中

        // 临时存储数据的窗口
        ControlWindow controlWindow = ControlWindow.getInstance();
        // 将submit以sequenceId作为标识,将submit存储到临时窗口
        controlWindow.put(sequenceId,submit);

        // 封装给移动运营商发送的消息.
        CmppMessageHeader submitMessage=new CmppSubmit(Command.CMPP2_VERSION, "", srcNumber, sequenceId, mobile, content);
        // 通过netty将封装好的消息发送给移动运营商
        nettyClient.submit(submitMessage);
    }


}
